package auction.auction;

import java.io.*;
import java.net.*;
import java.util.HashMap;

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import org.jaxen.jdom.JDOMXPath;
import org.jaxen.SimpleNamespaceContext;

import auction.commons.XTrustProvider;
import javax.net.ssl.HttpsURLConnection;

/**
 * RequestApplicationTicket
 * 
 * https://api.auction.co.kr/APIv1/Securityservice.asmx?op=RequestApplicationTicket
 * 
 * : http://api.auction.co.kr/developer
 * 
 */
public class RequestApplicationTicket {
    private final String SERVER_URL = "https://api.auction.co.kr/APIv1/Securityservice.asmx";		// 
	//private final String SERVER_URL = "https://apitest.auction.co.kr/APIv1/Securityservice.asmx";		// 
    private final String SOAP_AUCTION = "http://www.auction.co.kr/ServiceInterfaces/RequestApplicationTicket";
	
	private String devID = "";			// 
	private String appID = "";			//
	private String appPassword = "";	//
	
	public RequestApplicationTicket(String _devID, String _appID, String _appPassword) {
		devID = _devID;
		appID = _appID;
		appPassword = _appPassword;
	}
	
	public String doService() {
		String ticket = "";
		XTrustProvider.install();
        
        try
        {
            //Create a HttpsURLConnection with the correct server
            URL server = new URL(SERVER_URL);
            HttpURLConnection connection = (HttpURLConnection) (server.openConnection());
            //HttpsURLConnection connection = (HttpsURLConnection) (server.openConnection());	// SSL �����
            
            //Add the necessary headers to the connection
            addAuctionHTTPHeaders(connection, SOAP_AUCTION);
            
	        /* SOAP Request �ۼ� */
	        StringBuffer request_xml = new StringBuffer();
	        request_xml.append ("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			request_xml.append ("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
			request_xml.append ("  <soap:Body>");
			request_xml.append ("    <RequestApplicationTicket xmlns=\"http://www.auction.co.kr/ServiceInterfaces\">");
			request_xml.append ("      <req DevID=\"" + devID + "\" AppID=\"" + appID + "\" AppPassword=\"" + appPassword + "\" />");
			request_xml.append ("    </RequestApplicationTicket>");
			request_xml.append ("  </soap:Body>");
			request_xml.append ("</soap:Envelope>");
	        
	        //Print SOAP Request
	        System.out.println("****REQUEST SOAP****");
	        System.out.println(request_xml.toString().replaceAll("><", ">\r\n<"));
	        
            //Get the output stream of the connection
            OutputStream out = connection.getOutputStream();
            out.write(request_xml.toString().getBytes("UTF-8"));
	        out.flush();
	        out.close();
	        
            //Send the request and return the resulting XML document
	        Document xmlDoc = SendRequest(connection);
            //if null is returned then there was an error
            if(xmlDoc == null) return "";
            
            /* Process Response */
            System.out.println("\r\n****PROCESS RESPONSE****");
            HashMap map = new HashMap();
            //HashMap<String, String> map = new HashMap<String, String>();	// JDK 1.5
	        map.put("api", "http://www.auction.co.kr/ServiceInterfaces");	// Default Namespace ó��
	        
            JDOMXPath xPath = new JDOMXPath ("//api:RequestApplicationTicketResult");
	        xPath.setNamespaceContext( new SimpleNamespaceContext(map) );
            
            Element element = (Element) xPath.selectSingleNode(xmlDoc);
	        
            if (element != null){
            	ticket = element.getValue();
            }
            
        } catch(Exception e) {
        	e.printStackTrace();
        }
        
        return ticket;
	}
    /**
     * Sends the request to the Server and returns the Document (XML)
     * that is returned as the response.
     */    
    private Document SendRequest(HttpURLConnection connection) {
        try
        {
            //Get the Input stream for the response
            InputStream in = connection.getInputStream();
	        
	        //Get the XML file into a Document object
	        SAXBuilder builder = new SAXBuilder();
	        Document response = builder.build(in);
	        
	        //Print SOAP Response
            System.out.println("\r\n****RESPONSE SOAP****");
            XMLOutputter outputter = new XMLOutputter();
	        outputter.output(response, System.out);
	        
            //close the input stream and connection
            in.close();
            
            //return the response XML Document
            return response;
        } catch(IOException e) {
            System.out.println("SendRequest IO Error: " + e.toString());
            
            try {
            	InputStream es = connection.getErrorStream();
            	
            	//Get the XML file into a Document object
    	        SAXBuilder builder = new SAXBuilder();
    	        Document response = builder.build(es);
    	        
    	        //Print SOAP Response
                System.out.println("\r\n****ERROR SOAP****");
                
                //XMLOutputter outputter = new XMLOutputter();
                
                //OutputStream osLog = new FileOutputStream(LOG_ERROR_FILENAME);
                //outputter.output(response, osLog);
                //osLog.close();
                //outputter.output(response, System.out);
                
                JDOMXPath xPath = new JDOMXPath ("//faultstring");
                Element element = (Element) xPath.selectSingleNode(response);
                
                if (element != null){
                	System.out.println("faultstring : " + element.getValue());
                }
    	        
	    		es.close();
            } catch (Exception e2){}
            
            return null;
        } catch(Exception e) {
            System.out.println("Error Sending Request: " + e.toString());
            e.printStackTrace();
            
            return null;
        }
        finally {
        	if (connection != null) connection.disconnect();
        }
    }
    /**
     * Adds the necessary headers to the HttpsURLConnection passed in
     * order for the call to be successful
     */
    private void addAuctionHTTPHeaders(HttpURLConnection connection, String soapAction) throws ProtocolException
    {
    	connection.setRequestMethod("POST");
        connection.setRequestProperty("SOAPAction", soapAction);
        connection.setRequestProperty("Host", "api.auction.co.kr");
        connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
    	
    	connection.setDoInput(true);
    	connection.setDoOutput(true);
    }
}
